<template>
  <div class="echarts_box">
    <div class="echarts_box" ref="echarts_box" :style="{ opacity: data.length == 0 ? '0' : '1' }"></div>
    <!---------------------- 无数据是显示 ---------------------->
    <Nodata class="Nodata" v-show="data.length == 0"></Nodata>
  </div>
</template>


<script>
import { mapState, mapActions, mapGetters } from "vuex";
import fontSize from "@/modules/fontSize";
export default {
  props: {
    data: {
      // 返回的数据
      type: Array | Object,
      default: function () {
        return [];
      },
    },
    itemWidth: {
      type: Number | String,
      default: () => 1,
    },
    legendLeft: {
      type: String,
      default: () => "54%",
    },
    airLeft: {
      type: String | Number,
      default: () => 13,
    },
    itemHeight: {
      type: Number | String,
      default: () => 8,
    },
    imgWidth: {
      type: Number | String,
      default: () => 1,
    },
    imgLeft: {
      type: Number | String,
      default: () => 1,
    },
    labelLength: {
      type: Number | String,
      default: () => 2,
    },
    label: {
      type: String,
      default: () => "标准箱",
    },
    img: {
      // 图片地址
      type: Object | String,
      default: () => require("@/assets/images/echarts/bing.png"),
    },
    isTitle: {
      // 标题是否显示
      type: Boolean,
      default: () => false,
    },
    color: {
      //
      type: Array | Object,
      default: function () {
        return [
          "rgba(0,255,211,1)",
          "rgba(255,255,0,1)",
          "rgba(255,58,234,1)",
          "rgba(35,195,255,1)",
          "rgba(18,104,255,1)",
          "rgba(0,193,59,1)",
          "rgba(255,203,0,1)",
        ];
      },
    },
    length: {
      type: String | Number,
      default: () => 5,
    },
  },
  computed: {
    // ...mapGetters(["echartsColor"]),
  },
  data() {
    return {
      echartsColor: "#ffffff",
    };
  },
  watch: {
    data: "drawLine", // 数值变化是更新图表
    length: "drawLine", // 数值变化是更新图表
    isTitle: "drawLine", // 数值变化是更新图表
    itemWidth: "drawLine", // 数值变化是更新图表
    imgLeft: "drawLine", // 数值变化是更新图表
    imgWidth: "drawLine", // 数值变化是更新图表
    label: "drawLine", // 数值变化是更新图表
    legendLeft: "drawLine", // 数值变化是更新图表
    airLeft: "drawLine", // 数值变化是更新图表
    labelLength: "drawLine", // 数值变化是更新图表
  },
  mounted() {
    this.drawLine();
  },
  methods: {
    getArrayValue(array, key) {
      var key = key || "value";
      var res = [];
      if (array) {
        array.forEach(function (t) {
          res.push(t[key]);
        });
      }
      return res;
    },
    array2obj(array, key) {
      var resObj = {};
      for (var i = 0; i < array.length; i++) {
        resObj[array[i][key]] = array[i];
      }
      return resObj;
    },
    getData(data, sumValue) {
      var res = {
        series: [],
        yAxis: [],
      };
      var cw = document.body.clientWidth;
      let left = null;
      let itemWidth = fontSize.fontSize() * this.itemWidth;
      if (cw > 1200) {
        itemWidth = fontSize.fontSize() * this.itemWidth;
        left = Number(this.airLeft) / 2.2 + "%";
      } else {
        itemWidth = fontSize.fontSize() * this.itemWidth * 1.1;
        left = Number(this.airLeft) / 2.2 + "%";
      }
      for (let i = 0; i < data.length; i++) {
        res.series.push({
          name: "",
          type: "pie",
          clockWise: false, //顺时加载
          hoverAnimation: false, //鼠标移入变大
          radius: [
            65 - i * 15 + "%",
            60 - i * 15 + "%",
          ],
          width: itemWidth, //自适应大小,
          height: itemWidth, //自适应大小,
          center: ["50%", "50%"],
          top: "center",
          left: left,
          label: {
            show: false,
          },
          itemStyle: {
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            borderWidth: 6,
          },
          data: [
            {
              value: data[i].value,
              name: data[i].name,
              itemStyle: {
                color: this.color[i],
                shadowColor: this.color[i],
                // borderWidth: 5,
                shadowBlur: 4,
                // borderWidth: 0,
              },
            },
            {
              value: sumValue - data[i].value,
              name: "",
              itemStyle: {
                color: "rgba(0,0,0,0)",
                borderWidth: 0,
              },
              tooltip: {
                show: false,
              },
              hoverAnimation: false,
            },
          ],
        });
        res.series.push({
          name: "",
          type: "pie",
          silent: true,
          z: 1,
          clockWise: false, //顺时加载
          hoverAnimation: true, //鼠标移入变大
          radius: [
            65 - i * 15 + "%",
            60 - i * 15 + "%",
          ],
          width: itemWidth, //自适应大小,
          height: itemWidth, //自适应大小,
          center: ["50%", "50%"],
          top: "center",
          left: left,
          label: {
            show: false,
          },
          itemStyle: {
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            borderWidth: 6,
          },
          data: [
            {
              value: 7.5,
              itemStyle: {
                color: "#245285",
                borderWidth: 0,
              },
              tooltip: {
                show: false,
              },
              // barBorderRadius: 5,
              hoverAnimation: false,
            },
            {
              value: 2.5,
              name: "",
              itemStyle: {
                color: "rgba(0,0,0,0)",
                borderWidth: 0,
              },
              tooltip: {
                show: false,
              },
              hoverAnimation: false,
            },
          ],
        });
        // res.yAxis.push(((data[i].value / sumValue) * 100).toFixed(2) + "%");
        res.yAxis.push(data[i].value);
      }
      return res;
    },
    drawLine() {
      try {
        this.$nextTick(() => {
          var _this = this;
          var cw = document.body.clientWidth;

          var myChart = _this.$echarts.init(_this.$refs.echarts_box);
          let myData = [];
          myData = this.data;
          if (myData.length > this.length) {
            myData = myData.splice(0, this.length);
          }
          let title = {};
          let titleLeft =1
          if (this.labelLength > 1) {
            title = {
              fontSize: fontSize.fontSize(0.082),
              fontWeight: "bold",
              height: 15,
              // width: fontSize.fontSize(0.5),
              color: "rgba(212,240,255,1)",
            };
          } else {
            title = {
              fontSize: fontSize.fontSize(0.082),
              fontWeight: "bold",
              // padding: [0, 0, 0, 8],
              height: 15,
              color: "rgba(212,240,255,1)",
            };
          }
          var data = myData;
          var arrName = _this.getArrayValue(data, "name");
          var arrValue = _this.getArrayValue(data, "value");
          var sumValue = 0;
          for (let item of arrValue) {
            sumValue += item / 0.75;
          }
          let imgwidth = 1;
          if (this.isTitle == false || this.isTitle == "false") {
            imgwidth = this.imgWidth;
          } else {
            imgwidth = 0;
          }

          var sum = 0;
          for (var i = 0; i < myData.length; i++) {
            sum += myData[i].value;
          }
          let elements = []; //图标背景
          let itemWidth = fontSize.fontSize() * this.itemWidth;
          if (cw > 1200) {
            itemWidth = fontSize.fontSize() * this.itemWidth;
            titleLeft  =1
             if (this.isTitle != true) {
              elements = [
                {
                  type: "image",
                  z: -1,
                  style: {
                    image: this.img,
                    width: itemWidth / 3, //自适应大小,
                    height: itemWidth / 3, //自适应大小,
                  },
                  left: Number(this.airLeft) * 0.86 + "%",
                  top: "center",
                },
              ];
            }
           
          } else {
            itemWidth = fontSize.fontSize() * this.itemWidth * 1.2;
            titleLeft =1.2
            if (this.isTitle != true) {
              elements = [
                {
                  type: "image",
                  z: -1,
                  style: {
                    image: this.img,
                    width: itemWidth / 3, //自适应大小,
                    height: itemWidth / 3, //自适应大小,
                  },
                  left: Number(this.airLeft) * 0.97 + "%",
                  top: "center",
                },
              ];
            }
          }
          var mean = (arrValue[1]/arrValue[0]*100).toFixed(0);
          var objData = _this.array2obj(data, "name");
          var optionData = _this.getData(data, sumValue);
          var option = {
            title: {
              show: this.isTitle, //显示策略，默认值true,可选为：true（显示） | false（隐藏）
              text: mean + "%", //主标题文本，'\n'指定换行
              // link: "", //主标题文本超链接,默认值true
              // target: null, //指定窗口打开主标题超链接，支持'self' | 'blank'，不指定等同为'blank'（新窗口）
              subtext: "完成度", //副标题文本，'\n'指定换行
              // sublink: "", //副标题文本超链接
              // subtarget: null, //指定窗口打开副标题超链接，支持'self' | 'blank'，不指定等同为'blank'（新窗口）
              left:27.5  + "%", //水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
              y: "38%", //垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
              textAlign: "center", //水平对齐方式，默认根据x设置自动调整，可选为： left' | 'right' | 'center
              // backgroundColor: "rgba(0,0,0,0)", //标题背景颜色，默认'rgba(0,0,0,0)'透明
              // borderColor: "#ccc", //标题边框颜色,默认'#ccc'
              // borderWidth: 0, //标题边框线宽，单位px，默认为0（无边框）
              // padding: 5, //标题内边距，单位px，默认各方向内边距为5，接受数组分别设定上右下左边距
              itemGap: 2, //主副标题纵向间隔，单位px，默认为10
              textStyle: {
                //主标题文本样式{"fontSize": 18,"fontWeight": "bolder","color": "#333"}
                // fontFamily: "Arial, Verdana, sans...",
                fontSize: fontSize.fontSize(0.15),
                // fontStyle: "normal",
                // fontWeight: "normal",
                color: "rgba(0,255,211,1)",
                textShadowColor: "rgba(0,255,211,1)", //阴影颜色
                textShadowBlur: "10", //阴影的宽度
                textShadowOffsetX: "-1", //阴影向X偏移
                textShadowOffsetY: "-1", //阴影向Y偏移
              },
              subtextStyle: {
                //副标题文本样式{"color": "#aaa"}
                // fontFamily: "Arial, Verdana, sans...",
                // fontSize: 12,
                // fontStyle: "normal",
                // fontWeight: "normal",
                position: {
                  top: -30,
                },
                color: "rgba(255,255,255,0.9)",
                fontSize: fontSize.fontSize(0.082),
              },
            },
                graphic: {
              elements,
            },
            legend: {
              show: true,
              top: "center",
              left: this.legendLeft,
              orient: "vertical", //horizontal//横向//vertical//纵向
              data: arrName,
              // borderColor: "rgba(85, 150, 188,0.5)", //边框颜色
              // borderWidth: 1, //边框线宽
              // width: 50,
              // height: "10",
              // padding: [12, 19, 12, 19], //图例内边距，单位px  5  [5, 10]  [5,10,5,10]
              // itemGap: 25,
              itemWidth: 6,
              itemHeight: 6,
               itemGap:5,          
              textStyle: {
                color: this.echartsColor,
                fontSize: 11,
              },
              icon: "circle", //circle, rect, roundRect, triangle, diamond, pin, arrow, none
               formatter: (name) => {
                var index = 0;
                var legendData = option.legend.data;
                legendData.forEach(function (v, i) {
                  if (v == name) {
                    index = i;
                  }
                });
                if (this.labelLength > 1) {
                  return (
                    "{title|" +
                    name +
                    "}{value|" +
                    ((objData[name].value/sum)* 100).toFixed(1) +
                    this.label +
                    "%}"
                  );
                } else {
                  return "{title|" + name + "}{title|" +
                    ((objData[name].value/sum)* 100).toFixed(1)  +
                    this.label +
                    "%}";
                }
              },

              textStyle: {
                rich: {
                  title: title,
                  value: {
                    fontSize: fontSize.fontSize(0.08),
                    fontWeight: "bold",
                    height: 15,
                    // width: fontSize.fontSize(0.31),
                    align: "right",
                    // color: function (params) {
                    //   return colorList[params.dataIndex];
                    // },
                    color: "#ffffff",
                  },
                },
              },
            },
            tooltip: {
              show: true,
              trigger: "item",
              // formatter: "{b}:{c}({c}%)",
            },
            color: ["#59CCE2", "#FAC657", "#91CC75"],
            grid: {
              top: "14%",
              bottom: "64%",
              left: "34%",
              containLabel: false,
            },
            yAxis: [
              {
                type: "category",
                inverse: true,
                axisLine: {
                  show: false,
                },
                axisTick: {
                  show: false,
                },
                axisLabel: {
                  interval: 0,
                  inside: false,
                  textStyle: {
                    color: "rgba(212,240,255,0.8)",
                    fontSize: fontSize.fontSize(0.087),
                  },
                  show: false,
                },
                data: optionData.yAxis,
              },
            ],
            xAxis: [
              {
                show: false,
              },
            ],
            series: optionData.series,
          };
          myChart.setOption(option);
          myChart.off("click");
          /* 点击事件 */
          myChart.on("click", (params) => {});
          /* 大小自适应 */
          window.addEventListener("resize", function () {
            myChart.resize();
          });
          myChart.resize();
        });
      } catch (e) {
        // 错误处理代码片段
      }
    },
  },
};
</script>


<style lang="scss" scoped>
.echarts_box {
  width: 100%;
  height: 100%;
  position: relative;
  .Nodata {
    position: absolute;
    top: 0;
    z-index: 10;
  }
}
</style>  